package com.hanfb.mall.inventory.service.impl;

import com.hanfb.mall.inventory.request.ProductInventoryCacheReloadRequest;
import com.hanfb.mall.inventory.request.ProductInventoryDbUpdateRequest;
import com.hanfb.mall.inventory.request.Request;
import com.hanfb.mall.inventory.request.RequestQueue;
import com.hanfb.mall.inventory.service.RequestAsyncProcessService;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @作者： Hanfb
 * @描述： 请求异步执行的service 实现类
 * @时间： 2020年10月12日
 */
@Service
public class RequestAsyncProcessServiceImpl implements RequestAsyncProcessService {
    @Override
    public void process(Request request) {
        try {

            //作请求的路由 根据每个而请求的商品id 路由至对应的内存队列
            ArrayBlockingQueue<Request> queue = getRouteQueue(request.getProductId());
            //将请求放入对应的队列 完成路由操作

            queue.put(request);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public ArrayBlockingQueue<Request> getRouteQueue(Integer productId) {
        RequestQueue requestQueue = RequestQueue.getInstance();
        String key = String.valueOf(productId);
        int h;
        int hash = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        int index = (requestQueue.queueSize() - 1) & hash;
        System.out.println("===========日志============：路由内存队列，商品id="+productId+", 队列索引="+ index);
        return requestQueue.getQueue(index);
    }

}
